<?php


/**
 * iDaren 数据库server请求发送
 *
 * @param $options
 */
function dr_server_request($file, array $posts)
{
	$ch = curl_init();

	$posts_query = http_build_query($posts, null, '&');

	$opts = array(
		CURLOPT_URL => DR_SERVER_PATH . $file,
		CURLOPT_TIMEOUT => 100,
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_POST => true,
		CURLOPT_POSTFIELDS => $posts_query,
	);

	curl_setopt_array($ch, $opts);

	$data = curl_exec($ch);
	curl_close($ch);

	return $data;
}

/**
 * 用户标记问题的函数
 *
 * @param $user_id
 * @param $question_id
 * @param $mark_type
 */
function dr_mark_questions($user_id, $question_id, $mark_type)
{
	$posts = array(
		'action' => 'mark_question',
		'user_id' => $user_id,
		'question_id' => $question_id,
		'mark_type' => $mark_type
	);

	$result = json_decode(dr_server_request('dr-app-questions.php', $posts), true);

	return $result['ret'];
}

/**
 * 用户关注其他用户
 */
function dr_mark_users($user_id, $marked_user_id, $mark_type)
{
	$posts = array(
		'action' => 'mark_user',
		'user_id' => $user_id,
		'marked_user_id' => $marked_user_id,
		'mark_type' => $mark_type
	);

	$result = json_decode(dr_server_request('dr-app-users.php', $posts), true);

	return $result['ret'];
}

/**
 * 用户关注的标签
 */

function dr_mark_tags($user_id, $marked_tag_id, $mark_type)
{
	$posts = array(
		'action' => 'mark_tag',
		'user_id' => $user_id,
		'marked_tag_id' => $marked_tag_id,
		'mark_type' => $mark_type
	);

	$result = json_decode(dr_server_request('dr-app-tags.php', $posts), true);

	return $result['ret'];
}

/**
 * 设置最佳答案
 */

function dr_set_best($user_id, $question_id, $best_id, $set_type)
{
	$posts = array(
		'action' => 'set_best_answer',
		'user_id' => $user_id,
		'question_id' => $question_id,
		'best_id' => $best_id,
		'set_type' => $set_type
	);

	$result = json_decode(dr_server_request('dr-app-questions.php', $posts), true);

	return $result['ret'];
}

# ============================================== #
/*
 对明文密码进行加密
 返回：加密后的十六进制密码
 */
function dr_db_calc_passcheck($password, $salt)
{
	return sha1(substr($salt, 0, 8) . $password . substr($salt, 8));
}

//返回：带中文版本的substr
function dr_utf8_substr($string, $start = 0, $len = 30)
{
	$start_position = strlen($string);
	$end_position = strlen($string);
	$count = 0;
	$start_byte = 0;

	for ($i = 0; $i < strlen($string); $i++)
	{
		if ($count >= $start && $start_position >= $i) {
			$start_position = $i;
			$start_byte = $count;
		}
		if ($count - $start_byte >= $len) {
			$end_position = $i;
			break;
		}

		$value = ord(substr($string, $i, 1));
		if ($value > 127) {
			$count++;
			if ($value >= 192 && $value <= 223) //2字节
				$i++;
			else if ($value >= 224 && $value <= 239) //3字节
				$i = $i + 2;
			else if ($value >= 240 && $value <= 247) //4字节
				$i = $i + 3;
		}
		$count++;
	}
	return substr($string, $start_position, $end_position - $start_position);
}

//返回：如果字符串长度大于30，则截取前半部分；否则原样输出
function dr_cut_string($string, $len = 30)
{
	if (strlen($string) <= 30)
		return $string;
	else
	{
		$str = dr_utf8_substr($string, 0, $len);
		$str = $str . '...';
		return $str;
	}
}

/*
 返回：十六进制的随机字符串
 */
function dr_random_alphanum($length)
{
	$string = '';

	while (strlen($string) < $length)
		$string .= str_pad(base_convert(mt_rand(0, 46655), 10, 36), 3, '0', STR_PAD_LEFT);

	return substr($string, 0, $length);
}

/*
 修改username对应的登录时间
 */
function dr_db_set_logindate($username)
{
	$posts = array(
		'action' => 'set_login_date',
		'username' => $username
	);

	$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);
	return $data['ret'];
}


/*
 * 获取用户id
 */

function dr_db_user_id($username)
{
	$posts = array(
		'action' => 'get_userid',
		'username' => $username
	);

	$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);
	return $data['userid'];
}

# ============================================== #

# dr-app-user============================================= #
/*
 * 设置session过期时间，并开启一个会话
 */
function dr_start_session()
{
	@ini_set('session.gc_maxlifetime', 86400);
	@ini_set('session.use_trans_sid', false);

	if (!isset($_SESSION))
		session_start();
}

/*
 * 如果用户id存在，在会话中保存id，并将随机生成的session_code保存在数据库
 * 生成cookie，保存用户名和session_code
 *
 * 如果用户id不存在，则删除cookie，清空会话中的用户id
 */
# 登陆成功后session存取
function dr_set_logged_in_user($userid, $username = '', $remember = false)
{
	dr_start_session();
	if (isset($userid)) {
		$_SESSION['user_id'] = $userid;
		$session_code = dr_random_alphanum(8);
		//设置用户表中的session_code
		dr_user_set_session($userid, $session_code);
		//创建cookie，保存用户名
		dr_set_session_cookie($username, $session_code, $remember);
	} else {
		dr_user_set_session($_SESSION['user_id'], '');
		//删除cookie
		dr_clear_session_cookie();
		//释放会话中的用户id
		unset($_SESSION['user_id']);
	}
}

function dr_user_set_session($userid, $session_code)
{

	$posts = array(
		'action' => 'set_session',
		'userid' => $userid,
		'session_code' => $session_code
	);

	$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);
	return $data['ret'];
}

/*
 * 返回：登录用户的id，否则返回null
 */
function dr_get_logged_in_userid()
{
	global $dr_logged_in_userid_checked;

	if (! $dr_logged_in_userid_checked) {
		dr_start_session();
		if (!empty($_COOKIE['dr_session'])) {
			//获取cookie中存放的信息
			@list($username, $session_code, $remember) = explode('/', $_COOKIE['dr_session']);
			//重置cookie，使其保持有效时间不变
			if ($remember)
				dr_set_session_cookie($username, $session_code, $remember);
			$session_code = trim($session_code);
			if (!isset($_SESSION['user_id']) && !empty($username) && !empty($session_code)) {
				//获取数据库中的user_id和session_code
				$posts = array(
					'action' => 'get_session',
					'username' => $username
				);

				$row = json_decode(dr_server_request('dr-app-users.php', $posts), true);

				$session_code_db = $row['session_code'];
				$user_id = $row['user_id'];
				if (strtolower($session_code_db) == strtolower($session_code))
					$_SESSION['user_id'] = $user_id;
				else
					dr_clear_session_cookie();
			}
		}
		$dr_logged_in_userid_checked = true;
	}
	return @$_SESSION['user_id'];
}

function dr_get_logged_user() {
	if ($user_id = dr_is_login_on()) {
		$posts = array(
			'action' => 'get_user_profile',
			'user_id' => $user_id,
		);

		return json_decode(dr_server_request('dr-app-users.php', $posts), true);
	}
}

//设置cookie，保存用户名、session_code和是否记住密码
function dr_set_session_cookie($username, $session_code, $remember)
{
	setcookie('dr_session', $username . '/' . $session_code . '/' . ($remember ? 1 : 0), $remember ? (time() + 2592000) : 0, '/');
}

//清除cookie
function dr_clear_session_cookie()
{
	setcookie('dr_session', false, time() - 1, '/');
}

//判断用户是否处于登录状态
//返回：登录状态，返回user_id；否则，返回false
function dr_is_login_on()
{
	$userid = dr_get_logged_in_userid();
	if (!isset($userid)) {
		return false;
	} else {
		return $userid;
	}
}

# dr-app-user============================================= #

/*
 * 清除用户的新消息或者历史记录
 */
function dr_clear_record($user_id, $clear_type)
{
	$posts = array(
		'action' => 'clear_user_record',
		'clear_type' => $clear_type,
		'user_id' => $user_id
	);

	$result = json_decode(dr_server_request('dr-app-users.php', $posts), true);

	return $result['ret'];
}

# dr-app-login==================================== #
/*
 判断登录密码是否正确
 返回：如果用户名和密码正确，返回true；否则返回false
 */
function dr_is_password_correct($username, $password)
{
	$posts = array(
		'action' => 'get_passsalt_passcheck',
		'username' => $username
	);

	$result = json_decode(dr_server_request('dr-app-users.php', $posts), true);

	if (is_array($result)) {
		$passsalt = $result['passsalt'];
		$passcheck = $result['passcheck'];
		if (strtolower(dr_db_calc_passcheck($password, $passsalt)) == strtolower($passcheck)) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

/*
 判断用户登录是否成功
 返回：如果成功登录，返回true，否则返回false
 */
function dr_login($username, $password)
{
	$is_login = dr_is_password_correct($username, $password);
	if ($is_login) {
		dr_db_set_logindate($username); //更新登录时间
		return true;
	} else {
		return false;
	}

}

# 判断用户名输入是否合法
function dr_is_username_valid($username)
{
	if (strlen($username) < 6)
		return false;
	else
		return true;
}

/*
 判断用户名是否存在
 返回：如果存在，返回true，否则返回false
 */
function dr_is_username_exist($username)
{
	$posts = array(
		'action' => 'username_exist',
		'username' => $username
	);

	$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);
	return $data['ret'] ? true : false;
}

# 判断用户输入的密码是否合法
function dr_is_password_valid($password)
{
	return true;
}

/*
 判断邮箱是否有效
 返回：如果邮箱地址无效，返回1；邮箱已存在，返回2；邮箱有效，返回3
 */
function dr_is_email_valid($email)
{
	$email_pattern = '/^[^<>\s$@]+@([-[:alnum:]]+\.)+[[:lower:]]{2,}$/i';

	if (!preg_match($email_pattern, $email)) {
		return 1;
	}

	$posts = array(
		'action' => 'email_exist',
		'email' => $email
	);

	$data = json_decode(dr_server_request('dr-app-users.php', $posts), true);
	return $data['ret'] ? 2 : 3;
}

# dr-app-login======================================== #

# dr-app-vote=================================== #
function dr_up_vote($id, $type, $owner_id)
{
	switch ($type) {
		case 'question':
			$action = 'question_up_vote';
			break;

		case 'reply':
			$action = 'answer_up_vote';
			break;

		case 'comment':
			$action = 'comment_up_vote';
			break;
	}

	$user_id = dr_get_logged_in_userid();
	$posts = array(
		'action' => $action,
		'id' => $id,
		'user_id' => $user_id,
		'owner_id' => $owner_id
	);

	$ret = json_decode(dr_server_request('dr-app-votes.php', $posts), true);
	return $ret['ret'];
}


//问题和回答被踩时，设置down_votes_num加一
function dr_down_vote($id, $type, $owner_id)
{
	switch ($type) {
		case 'question':
			$action = 'question_down_vote';
			break;

		case 'reply':
			$action = 'answer_down_vote';
			break;

		case 'comment':
			$action = 'comment_down_vote';
			break;
	}

	$user_id = dr_get_logged_in_userid();
	$posts = array(
		'action' => $action,
		'id' => $id,
		'user_id' => $user_id,
		'owner_id' => $owner_id
	);

	$ret = json_decode(dr_server_request('dr-app-votes.php', $posts), true);
	return $ret['ret'];
}
# dr-app-vote================================= #
